<?php
declare(strict_types=1);

namespace app\controller\merchant;

use app\BaseController;
use app\model\{Order, UserBalanceFlow, MerchantFundFlow};
use app\service\{WechatService, AlipayService};
use think\facade\{Db, Log};
use think\Request;

class RefundController extends BaseController
{
    /**
     * 获取退款订单列表
     */
    public function list(Request $request)
    {
        try {
            $params = $request->get();
            $merchant_id = $request->merchant_id;
            $page = $params['page'] ?? 1;
            $limit = $params['limit'] ?? 15;
            
            $where = [
                ['merchant_id', '=', $merchant_id],
                ['refund_status', '<>', 0] // 有退款记录的订单
            ];
            
            // 状态筛选
            if (isset($params['refund_status'])) {
                $where[] = ['refund_status', '=', $params['refund_status']];
            }
            
            // 时间范围筛选
            if (!empty($params['start_time'])) {
                $where[] = ['create_time', '>=', $params['start_time']];
            }
            if (!empty($params['end_time'])) {
                $where[] = ['create_time', '<=', $params['end_time']];
            }
            
            $list = Order::where($where)
                ->with(['user'])
                ->order('id', 'desc')
                ->paginate([
                    'list_rows' => $limit,
                    'page' => $page
                ]);
            
            return json(['code' => 0, 'msg' => '获取成功', 'data' => $list]);
        } catch (\Exception $e) {
            Log::error('获取退款订单列表失败: ' . $e->getMessage());
            return json(['code' => 1, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 处理退款申请
     */
    public function process(Request $request)
    {
        Db::startTrans();
        try {
            $params = $request->post();
            $merchant_id = $request->merchant_id;
            
            // 验证参数
            if (empty($params['order_no']) || !isset($params['status'])) {
                return json(['code' => 1, 'msg' => '参数错误']);
            }
            
            // 获取订单信息
            $order = Order::where([
                'order_no' => $params['order_no'],
                'merchant_id' => $merchant_id
            ])->find();
            
            if (!$order) {
                return json(['code' => 1, 'msg' => '订单不存在']);
            }
            
            if ($order->refund_status != 1) { // 1:申请中
                throw new \Exception('订单退款状态错误');
            }
            
            // 同意退款
            if ($params['status'] == 1) {
                // 原路退款
                if ($order->payment_method == 1) { // 微信支付
                    $wechatService = new WechatService($merchant_id);
                    $result = $wechatService->refund([
                        'out_trade_no' => $order->order_no,
                        'total_fee' => $order->fee_actual * 100,
                        'refund_fee' => $order->refund_amount * 100,
                        'refund_desc' => $params['remark'] ?? '订单退款'
                    ]);
                    if (!$result) {
                        throw new \Exception('微信退款失败');
                    }
                } else if ($order->payment_method == 2) { // 支付宝
                    $alipayService = new AlipayService($merchant_id);
                    $result = $alipayService->refund([
                        'out_trade_no' => $order->order_no,
                        'refund_amount' => $order->refund_amount,
                        'refund_reason' => $params['remark'] ?? '订单退款'
                    ]);
                    if (!$result) {
                        throw new \Exception('支付宝退款失败');
                    }
                } else if ($order->payment_method == 3) { // 余额支付
                    // 退回用户余额
                    User::where('id', $order->user_id)->update([
                        'balance' => Db::raw('balance+' . $order->refund_amount)
                    ]);
                    
                    // 记录用户余额流水
                    UserBalanceFlow::create([
                        'user_id' => $order->user_id,
                        'merchant_id' => $merchant_id,
                        'type' => 4, // 退款
                        'amount' => $order->refund_amount,
                        'order_no' => $order->order_no,
                        'status' => 1,
                        'create_time' => date('Y-m-d H:i:s')
                    ]);
                }
                
                // 更新订单状态
                $order->save([
                    'refund_status' => 2, // 已退款
                    'refund_time' => date('Y-m-d H:i:s'),
                    'refund_remark' => $params['remark'] ?? ''
                ]);
                
                // 记录商家资金流水
                MerchantFundFlow::create([
                    'merchant_id' => $merchant_id,
                    'fund_flow_type' => 4, // 退款
                    'fund_flow_amount' => -$order->refund_amount,
                    'order_no' => $order->order_no,
                    'create_time' => date('Y-m-d H:i:s')
                ]);
            }
            // 拒绝退款
            else {
                $order->save([
                    'refund_status' => 3, // 已拒绝
                    'refund_time' => date('Y-m-d H:i:s'),
                    'refund_remark' => $params['remark'] ?? ''
                ]);
            }
            
            Db::commit();
            return json(['code' => 0, 'msg' => '处理成功']);
        } catch (\Exception $e) {
            Db::rollback();
            Log::error('处理退款申请失败: ' . $e->getMessage());
            return json(['code' => 1, 'msg' => $e->getMessage()]);
        }
    }
} 